//
//  ViewController.m
//  TheProjectName
//
//  Created by 李劲成 on 16/5/21.
//  Copyright © 2016年 sunzhichao. All rights reserved.
//

#import "RegisterVC.h"

#define MAIN_SCREEN [UIScreen mainScreen].bounds.size

#define COLOR [UIColor colorWithRed:0.52 green:0.35 blue:0.25 alpha:1.00]

#define COLOR_BACK [UIColor colorWithRed:0.96 green:0.92 blue:0.83 alpha:1.00]

@interface RegisterVC () <UITextFieldDelegate>

@property (nonatomic, retain) UIImageView *imageViewOfSun;

@property (nonatomic, retain) UITextField *textFieldOfUser;
@property (nonatomic, retain) UITextField *textFieldOfPassword;
@property (nonatomic, retain) UITextField *textFieldOfDefine;

@property (nonatomic, retain) UIButton *buttonOfDefine;
@property (nonatomic, retain) UIButton *buttonOfCancel;

@end

@implementation RegisterVC

- (void)viewWillAppear:(BOOL)animated
{
    self.buttonOfDefine.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 1000 , 300, 40);
    
    self.buttonOfCancel.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 1000 , 300, 40);
}

- (void)viewDidAppear:(BOOL)animated
{
    //弹性动画
    //damping:阻尼，范围0-1，阻尼越接近于0，弹性效果越明显
    //velocity:弹性复位的速度
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionAllowUserInteraction  animations:^{
        self.buttonOfDefine.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 380 , 300, 40);
    } completion:^(BOOL finished) {
    }];
    
    [UIView animateWithDuration:1 delay:0.5 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionAllowUserInteraction  animations:^{
        self.buttonOfCancel.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 430 , 300, 40);
    } completion:^(BOOL finished) {
    }];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self cretaeSubviews];
    
}

#pragma mark - create Subviews
- (void)cretaeSubviews
{
    // 背景图片
    NSString *path = [[NSBundle mainBundle]pathForResource:@"tree"ofType:@"jpg"];
    
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    
    self.view.layer.contents = (id)image.CGImage;
    
    // 添加太阳视图
    self.imageViewOfSun = [[UIImageView alloc] init];
    self.imageViewOfSun.frame = CGRectMake(40, 25, 80, 80);
    self.imageViewOfSun.image = [UIImage imageNamed:@"sun"];
    [self.view addSubview:self.imageViewOfSun];
    
    // 添加太阳动画
    [self startAnimationForSun];
    
    // 添加注册的所有textField
    [self createRegister];
}

#pragma mark - 添加注册视图
- (void)createRegister
{
    // 注册视图view
    UIView *viewOfRegister = [[UIView alloc] init];
    viewOfRegister.frame = CGRectMake(15, 130, MAIN_SCREEN.width - 30, 210);
    viewOfRegister.layer.borderWidth = 1.0f;
    viewOfRegister.layer.borderColor = COLOR.CGColor;
    viewOfRegister.layer.cornerRadius = 8.0f;
    viewOfRegister.backgroundColor = COLOR_BACK;
    viewOfRegister.alpha = 0.8f;
    [self.view addSubview:viewOfRegister];
    
    // 用户名textField
    self.textFieldOfUser = [[UITextField alloc] init];
    self.textFieldOfUser.frame = CGRectMake(30, 30, viewOfRegister.frame.size.width - 60, 44);
    self.textFieldOfUser.delegate = self;
    self.textFieldOfUser.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.textFieldOfUser.layer.cornerRadius = 8.0f;
    self.textFieldOfUser.layer.borderColor = COLOR.CGColor;
    self.textFieldOfUser.layer.borderWidth = 0.8f;
    self.textFieldOfUser.placeholder = @"请输入用户名";
    // 加入取消
    self.textFieldOfUser.clearButtonMode = UITextFieldViewModeAlways;
    // 修改用户名的placeholder的字体颜色
    NSMutableAttributedString *placeholderOfUser = [[NSMutableAttributedString alloc] initWithString:self.textFieldOfUser.placeholder];
    [placeholderOfUser addAttribute:NSForegroundColorAttributeName
                              value:COLOR
                              range:NSMakeRange(0, self.textFieldOfUser.placeholder.length)];
    self.textFieldOfUser.attributedPlaceholder = placeholderOfUser;
    // 用户名视图的左视图
    self.textFieldOfUser.leftView = [[UIView alloc] init];
    self.textFieldOfUser.leftView.frame = CGRectMake(0, 0, 44, 44);
    self.textFieldOfUser.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *imageViewOfUser = [[UIImageView alloc] init];
    imageViewOfUser.frame = CGRectMake(11, 11, 22, 22);
    imageViewOfUser.image = [UIImage imageNamed:@"user"];
    
    [self.textFieldOfUser.leftView addSubview:imageViewOfUser];
    [viewOfRegister addSubview:self.textFieldOfUser];
    
    //密码textField
    self.textFieldOfPassword = [[UITextField alloc] init];
    self.textFieldOfPassword.frame = CGRectMake(30, 90, viewOfRegister.frame.size.width - 60, 44);
    self.textFieldOfPassword.delegate = self;
    self.textFieldOfPassword.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.textFieldOfPassword.layer.cornerRadius = 8.0f;
    self.textFieldOfPassword.layer.borderColor = COLOR.CGColor;
    self.textFieldOfPassword.layer.borderWidth = 0.8f;
    self.textFieldOfPassword.placeholder = @"请输入密码";
    // 加入取消
    self.textFieldOfPassword.clearButtonMode = UITextFieldViewModeAlways;
    // 修改placeholder的字体颜色
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:self.textFieldOfPassword.placeholder];
    [placeholder addAttribute:NSForegroundColorAttributeName
                        value:COLOR
                        range:NSMakeRange(0, self.textFieldOfPassword.placeholder.length)];
    self.textFieldOfPassword.attributedPlaceholder = placeholder;
    // 密码视图的左视图
    self.textFieldOfPassword.leftView = [[UIView alloc] init];
    self.textFieldOfPassword.leftView.frame = CGRectMake(0, 0, 44, 44);
    self.textFieldOfPassword.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *imageViewOfPassword = [[UIImageView alloc] init];
    imageViewOfPassword.frame = CGRectMake(11, 11, 22, 22);
    imageViewOfPassword.image = [UIImage imageNamed:@"password"];
    self.textFieldOfPassword.secureTextEntry = YES;
    
    [self.textFieldOfPassword.leftView addSubview:imageViewOfPassword];
    [viewOfRegister addSubview:self.textFieldOfPassword];
    
    //再次确认密码textField
    self.textFieldOfDefine = [[UITextField alloc] init];
    self.textFieldOfDefine.frame = CGRectMake(30, 150, viewOfRegister.frame.size.width - 60, 44);
    self.textFieldOfDefine.delegate = self;
    self.textFieldOfDefine.layer.cornerRadius = 8.0f;
    self.textFieldOfDefine.layer.borderColor = COLOR.CGColor;
    self.textFieldOfDefine.layer.borderWidth = 0.8f;
    self.textFieldOfDefine.placeholder = @"请再次输入密码";
    // 加入取消
    self.textFieldOfDefine.clearButtonMode = UITextFieldViewModeAlways;
    // 修改placeholder的字体颜色
    NSMutableAttributedString *placeholderOfDefine = [[NSMutableAttributedString alloc]initWithString:self.textFieldOfDefine.placeholder];
    [placeholderOfDefine addAttribute:NSForegroundColorAttributeName
                                value:COLOR
                                range:NSMakeRange(0, self.textFieldOfDefine.placeholder.length)];
    self.textFieldOfDefine.attributedPlaceholder = placeholderOfDefine;
    // 密码视图的左视图
    self.textFieldOfDefine.leftView = [[UIView alloc] init];
    self.textFieldOfDefine.leftView.frame = CGRectMake(0, 0, 44, 44);
    self.textFieldOfDefine.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *imageViewOfDefine = [[UIImageView alloc] init];
    imageViewOfDefine.frame = CGRectMake(11, 11, 22, 22);
    imageViewOfDefine.image = [UIImage imageNamed:@"password"];
    self.textFieldOfDefine.secureTextEntry = YES;
    
    [self.textFieldOfDefine.leftView addSubview:imageViewOfDefine];
    [viewOfRegister addSubview:self.textFieldOfDefine];
    
    // 确定按钮
    self.buttonOfDefine = [UIButton buttonWithType:UIButtonTypeSystem];
    //    self.buttonOfDefine.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 380 , 300, 40);
    self.buttonOfDefine.layer.masksToBounds = YES;
    self.buttonOfDefine.layer.borderWidth = 1.0f;
    self.buttonOfDefine.layer.borderColor = COLOR.CGColor;
    self.buttonOfDefine.layer.cornerRadius = 8.0f;
    [self.buttonOfDefine setTitle:@"确定" forState:UIControlStateNormal];
    [self.buttonOfDefine addTarget:self action:@selector(handleDefine:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.buttonOfDefine];
    self.buttonOfDefine.titleLabel.font = [UIFont systemFontOfSize:22];
    [self.buttonOfDefine setTitleColor:COLOR forState:UIControlStateNormal];
    
    // 取消button
    self.buttonOfCancel = [UIButton buttonWithType:UIButtonTypeSystem];
    //    self.buttonOfCancel.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 430 , 300, 40);
    self.buttonOfCancel.layer.masksToBounds = YES;
    self.buttonOfCancel.layer.borderWidth = 1.0f;
    self.buttonOfCancel.layer.borderColor = COLOR.CGColor;
    self.buttonOfCancel.layer.cornerRadius = 8.0f;
    [self.buttonOfCancel setTitle:@"取消" forState:UIControlStateNormal];
    [self.buttonOfCancel addTarget:self action:@selector(handleCancel:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.buttonOfCancel];
    self.buttonOfCancel.titleLabel.font = [UIFont systemFontOfSize:22];
    [self.buttonOfCancel setTitleColor:COLOR forState:UIControlStateNormal];
}

#pragma mark - 确定事件
- (void)handleDefine:(UIButton *)button
{
    BOOL user = [AccountPrecdite filterUser:_textFieldOfUser.text completionHandle:^(UsernameError usernameError) {
        switch (usernameError) {
            case UsernameNil:
                presentAlert(self, @"用户名为空", @"请重新输入用户名");
                break;
            case UsernameIllegal:
                presentAlert(self, @"用户名不合法", @"请重新输入用户名");
                break;
            default:
                break;
        }
    }];
    
    BOOL password = [AccountPrecdite filterPassword:_textFieldOfPassword.text repeatedPassword:_textFieldOfDefine.text completionHandle:^(PasswordError passwordError) {
        switch (passwordError) {
            case PasswordNil:
                presentAlert(self, @"密码为空", @"请重新输入密码");
                break;
            case PasswordIllegal:
                presentAlert(self, @"密码不合法", @"包含大小写字母和数字的组合，不能使用特殊字符，长度在6-10之间。");
                break;
            case PasswordsIncompatible:
                presentAlert(self, @"两次密码不匹配", @"请确认后再输入");
                break;
            default:
                break;
        }
    }];
    if (password && user) {
        EMError *error = [[EMClient sharedClient] registerWithUsername:_textFieldOfUser.text password:_textFieldOfPassword.text];
        if (error==nil) {
         
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }
    }
    
}

#pragma mark - 取消事件
- (void)handleCancel:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - 太阳动画
- (void)startAnimationForSun
{
    CABasicAnimation *animattion = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    
    // 设置动画起止值
    animattion.fromValue=@(0);
    animattion.toValue=@(M_PI * 2);
    
    // 时间
    animattion.duration = 3.5;
    
    // 旋转效果累计, 设置为开的状态
    animattion.cumulative = YES;
    
    // 重复次数
    animattion.repeatCount = 1000;
    
    // 是否在动画结束后从layer上移除
    animattion.removedOnCompletion=NO;
    
    // 添加动画
    [self.imageViewOfSun.layer addAnimation:animattion forKey:nil];
}

#pragma mark - 点击空白处收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.textFieldOfUser resignFirstResponder];
    [self.textFieldOfPassword resignFirstResponder];
    [self.textFieldOfDefine resignFirstResponder];
}

#pragma mark - 当按return时的事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.textFieldOfPassword resignFirstResponder];
    [self.textFieldOfUser resignFirstResponder];
    [self.textFieldOfDefine resignFirstResponder];
    return YES;
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dismiss:(UIAlertController *)alert {
    [alert dismissViewControllerAnimated:YES completion:^{
        
    }];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
